package com.web.my12306.controller;


import com.alibaba.fastjson.JSON;
import com.web.my12306.dao.ISeatDao;
import com.web.my12306.dao.ITrainDao;
import com.web.my12306.dao.impl.SeatDaoImpl;
import com.web.my12306.dao.impl.TrainDaoImpl;
import com.web.my12306.pojo.EasyUIDataGridJSON;
import com.web.my12306.pojo.Orders;
import com.web.my12306.pojo.Seat;
import com.web.my12306.pojo.Train;
import com.web.my12306.service.OrderService;
import com.web.my12306.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class OrderServlet extends InnerDispatcherController
{

    private OrderService orderService = new OrderServiceImpl();

    List<Orders> orders = new ArrayList<>();
    List<Train> trains = new ArrayList<>();
    ISeatDao seatDao = new SeatDaoImpl();
    ITrainDao trainDao = new TrainDaoImpl();
    Seat seat = new Seat();
    Orders order = new Orders();

    /***
     * 黄逸
     ***/
    //根据oid查询订单详情
    public void queryByOid(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        int oid = Integer.parseInt(request.getParameter("oid"));
        order = orderService.queryByOid(oid);


        response.setContentType("application/json");
        response.getWriter().append(JSON.toJSONString(order));
        System.out.println(JSON.toJSONString(order));
    }

    /***
     * 黄逸
     ***/
    //获取该用户所有订单
    public void getAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        int uid = 0;
        try
        {
            uid = Integer.parseInt(request.getSession().getAttribute("uid").toString());
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }
        //int uid = 1;

        int page = 0;
        int rows = 0;
        try
        {
            page = Integer.valueOf(request.getParameter("page"));
            rows = Integer.valueOf(request.getParameter("rows"));
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }


        int start = (page - 1) * rows;//page从1开始的，减一，开始数据index
        orders = orderService.getAll(uid);
        //并没有太大优势的sql分页查询，因为反正要查总数，
        List<Orders> pageList = orderService.getByUserPage(uid, start, rows);
        //pageList页面显示的数据的list
        //        List<Orders> pageList=new ArrayList<>();
        //从所有的列表中取出第start到第start+row即第page页的数据
        //主意循环条件的i<orders.size()，否则最后一页数据小于rows报错，list越界
        //        for (int i = start; i < start + rows&&i<orders.size(); i++) {
        //            pageList.add(orders.get(i));
        //        }

        EasyUIDataGridJSON responseObject = new EasyUIDataGridJSON();
        responseObject.setTotal(orders.size());//数据总数，方便显示有多少页，限制页面超出
        responseObject.setRows(pageList);//页面显示数据的list

        response.setContentType("application/json");
        response.getWriter().append(JSON.toJSONString(responseObject));

    }

    /***
     * 黄逸
     ***/
    //购票
    public void check(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Orders order = new Orders();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //从页面获取
        int tid = 0;
        try
        {
            String id = request.getParameter("tid");
            System.out.println(id);
            tid = Integer.valueOf(id);
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }
        int uid = Integer.parseInt(request.getSession().getAttribute("uid").toString());

        //可购买车票list
        List<Seat> seats = new ArrayList<>();
        seats = seatDao.get(tid, 1);
        PrintWriter out = response.getWriter();
        //Seat seat=new Seat();
        if (seats.size() > 0)
        {
            //seat =seats.get((int)(seats.size()*Math.random()));

            orderService.add(uid, seats.get(0));
            out.print("success");
        }
        else

        {
            out.print("fail1");
        }

    }

    /**
     * 退票
     * 郭明亮
     */
    public void cancelOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String oidstr = request.getParameter("oid");

        String uidstr = request.getSession().getAttribute("uid").toString().trim();
        int uid = Integer.valueOf(uidstr);
        int oid = Integer.valueOf(oidstr);
        Orders orders = orderService.queryByOid(oid);
        PrintWriter out = response.getWriter();
        if (uid == orders.getUid())
        {
            if (2 == orders.getState() || 1 == orders.getState())
            {
                orderService.cancelOrder(oid);
                out.print("success");
            }
            else
            {
                out.print("error1");
            }
        }
        else
        {
            out.print("fail1");
        }

    }

    public void payOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String oidstr = request.getParameter("oid");
        String uidstr = request.getSession().getAttribute("uid").toString();
        int uid = Integer.valueOf(uidstr);
        int oid = Integer.valueOf(oidstr);
        Orders orders = orderService.queryByOid(oid);
        PrintWriter out = response.getWriter();
        if (uid == orders.getUid())
        {
            if (1 == orders.getState())
            {
                orderService.pay(oid);
                out.print("success");
            }
            else
            {
                out.print("error1");
            }
        }
        else
        {
            out.print("fail1");
        }
    }

    public void printOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String oidstr = request.getParameter("oid");
        String uidstr = request.getSession().getAttribute("uid").toString();
        int uid = 0;
        int oid = 0;
        try
        {
            uid = Integer.valueOf(uidstr);
            oid = Integer.valueOf(oidstr);
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }
        Orders orders = orderService.queryByOid(oid);
        PrintWriter out = response.getWriter();
        if (uid == orders.getUid())
        {
            if (2 == orders.getState())
            {
                               orderService.print(oid);
                response.setContentType("application/json");
                response.getWriter().append(JSON.toJSONString(orders));
            }
            else
            {
                out.print("error1");
            }
        }
        else
        {
            out.print("fail1");
        }
    }
}
